<template>
  <div style="height: 100%" v-loading="loading">
    <van-nav-bar title="成品预收货信息" left-text="返回" left-arrow @click-left="goBack" :right-text="postingDate"
      @click-right="setPostDate" />
    <van-calendar v-model="showCalendar" @confirm="onConfirm" :min-date="minDate" :max-date="maxDate"/>
    <van-cell-group :v-model="tableData" style="
        overflow: scroll;
        height: 520px;
      ">
      <van-field v-model="tableData.materialno" label="物料编码" readonly />
      <van-field v-model="tableData.materialdes" label="物料描述" readonly />
      <van-field v-model="tableData.batchno" label="批号" readonly />
      <van-field v-model="tableData.packinglotno" label="包装批" readonly />
      <van-field v-model="tableData.productionlotno" label="生产批" readonly />
      <!--      <van-row>-->
      <!--        <van-col span="12">-->
      <!--        </van-col>-->
      <!--        <van-col span="12">-->
      <!--        </van-col>-->
      <!--      </van-row>-->
      <van-field v-model="tableData.productionno" label="生产订单" readonly />
      <van-row>
        <van-col span="12">
          <van-field v-model="tableData.orderquantity" label="订单数量" readonly />
        </van-col>
        <van-col span="12">
          <van-field v-model="tableData.quantityreceived" label="已入数量" readonly />
        </van-col>
      </van-row> 
      <van-field v-model="tableData.totalquantity" label="入库总数量" readonly />
      <van-form v-for="(domain, domainIndex) in tableData.location" :key="domainIndex">
        <van-row style="border: solid 1px #3793fb; border-radius: 5px">
          <van-col span="12">
            <el-autocomplete v-model="domain.codeanddes" value-key="codeanddes" :rules="{
    required: true,
    message: '请选择库位',
    trigger: 'blur',
  }" @input="locationChange" :fetch-suggestions="storageLocationSearch" placeholder="选择库位" label="库位"
              @select="storageLocationHandleSelect"></el-autocomplete>
          </van-col>
          <van-col span="8">
            <van-field type="digit" label="数量:" @input="locationChange" v-model="domain.noofbarrels" label-width="45%"
              required />
          </van-col>
          <van-col span="4" style="text-align: left; border-left: red dashed 1px">
            <van-button icon="delete" type="primary" @click="removeDomain(domain)" style="
                color: red;
                background-color: transparent;
                border: none;
                width: 100%;
                font-size: small;
              ">删除</van-button>
          </van-col>
        </van-row>
      </van-form>
      <van-button type="primary" @click="addDomain" block style="
          width: 100%;
          background-color: white;
          border: #808080 1px dashed;
          margin-top: 20px;
          color: #3793fb;
        ">+ 增加库位</van-button>
    </van-cell-group>
    <van-button @click="onSubmit" style="
        position: fixed;
        bottom: 0px;
        border: #3793fb solid 1px;
        border-radius: 2px;
        background-color: #3793fb;
        line-height: var(--footer-height);
      " type="primary" block>预收货过账</van-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tableData: {
        materialno: "",
        batchno: "",
        materialdes: "",
        customerlotno: "",
        specification: "",
        productionno:"",
        totalquantity: "",
        location: [
          {
            location: "",
            locationdes: "",
            codeanddes:"",
            noofbarrels: "",
            quantity: ""
          }
        ]
      },
      storageLocationList: [],
      loading: false,
      showCalendar: false,
      postingDate: this.getNowFormatDate(new Date()),
      minDate:this.getMonthBeforeDate(),
      maxDate:this.getMonthAfterDate()
    };
  },
  mounted() {
    //成品入库信息
    this.getProductionInboundList(this.$route.query.codeInfo);
    //获取库位List
    this.getStorageLocationList();
  },
  methods: {
    setPostDate() {
      this.showCalendar = true;
    },
    onConfirm(date) {
      this.showCalendar = false;
      this.$dialog.confirm({
        title: '过账日期',
        message: '此选择将更改ERP过账日期',
      })
        .then(() => {
          this.postingDate = this.getNowFormatDate(date);
        })
        .catch(() => {
        });
    },
    async getProductionInboundList(codeInfo) {
      let scanInfo = {
        code: codeInfo + "," + localStorage.getItem("plant"),
      };
      const { data: res } = await this.$http.post(
        "/GetProductionInboundList",
        scanInfo
      );
      this.tableData = res[0];
    },
    async getStorageLocationList() {
      let scanInfo = {
        plant: localStorage.getItem("plant"),
      };
      const { data: res } = await this.$http.post(
        "/StorageLocationList",
        scanInfo
      );
      this.storageLocationList = res;
    },
    //返回
    goBack() {
      this.backToHome();
    },
    //入库过账
    onSubmit() {
      this.loading = true;
      setTimeout(() => {
        this.loading = false;
        this.postRawMaterialInbound();
      }, 1000);
    },
    handlePageChange(currentPage) {
      this.index = currentPage - 1;
    },
    //新增库位信息
    addDomain() {
      if (this.tableData.location === undefined) {
        this.tableData.location = [];
      }
      this.tableData.location.push({
        location: "",
        locationdes: "",
        noofbarrels: "",
        quantity: "",
        codeanddes: "",
      });
    },
    //删除库位信息
    removeDomain(item) {
      var index = this.tableData.location.indexOf(item);
      if (index !== -1) {
        this.tableData.location.splice(index, 1);
      }
      this.locationChange();
    },
    //库位搜索帮助
    storageLocationSearch(queryString, cb) {
      var storageLocationList = this.storageLocationList;
      var results = queryString
        ? storageLocationList.filter(this.createFilter(queryString))
        : storageLocationList;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (storageLocation) => {
        return (
          storageLocation.codeanddes
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) !== -1
        );
      };
    },
    //选择库位桶数自动计算总数量
    storageLocationHandleSelect() {
      // this.locationChange();
    },
    //自动计算总数量
    locationChange() {
       var locationList = this.tableData.location;
      var totalQuantity = 0;
       for (var i in locationList) {
         if (
           locationList[i].codeanddes != "" &&
           locationList[i].noofbarrels != ""
         ) {
           locationList[i].quantity =
             locationList[i].noofbarrels;
           totalQuantity = totalQuantity + parseInt(locationList[i].noofbarrels);
         }
       }
       this.tableData.totalquantity = totalQuantity ;
    },
    //过账接口
    async postRawMaterialInbound() {
      var requestData = this.tableData;
      var location = [];
      for (var i in requestData.location) {
        location.push({
          location: requestData.location[i].codeanddes.split("|")[0],
          stock:
            requestData.location[i].quantity,
        });
      }
      let inputInfo = {
        materialNo: requestData.materialno,
        plant: localStorage.getItem("plant"),
        batchNo: requestData.batchno,
        productionNo: requestData.productionno,
        postDate:this.postingDate,
        userName:  localStorage.getItem("erpId"),
        location:location
      };
      const { data: res } = await this.$http.post(
        "/PostProductionInbound",
        inputInfo
      );
      var response = res[0];
      if (response.type == "S") {
        this.$toast.success(response.message);
        setTimeout(() => {
          this.$router.push("/HomePage");
        }, 1000);
      } else if (response.type == "E") {
        this.$message({
          message: response.message,
          type: "error",
        });
      } else {
        this.$message({
          message: "入库失败，请联系系统维护人员",
          type: "error",
        });
      }
    },
  },
}
</script>

<style>
.el-input__inner {
  border: 0px;
  outline: none;
}
</style>